<template>
  <PPMPage v-if="pageData.length > 0" :formData="formData" :pageData="pageData">
    <template slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="24" class="text-center">
          <el-button type="primary" size="medium" @click="submitFun">保存</el-button>
          <el-button size="medium" @click="closeFun">关闭</el-button>
        </el-col>
      </el-row>
    </template>
  </PPMPage>
</template>
<script>
import ppmmixin from "@/mixins/ppmmixin.js";
import { mapState } from "vuex";
import OrderService from "@/api/order/OrderService.js";
export default {
  name: "PPMBatchEditDemand",
  mixins: [ppmmixin],
  data () {
    return {
      result: [],
      ppmParams: {},
      orderItemIds: '',
    };
  },
  computed: {
    ...mapState("user", ["user", "busiManagerId", "custManagerId"]),
  },
  props: {
    ODKInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    CTOInfo: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  async mounted () {
    //ppm的请求参数
    this.ppmParams = {
      "offerId": 10010021, 
      "productId": 80008007, 
      "prodName": "MSTP", 
      "serviceOfferId": "1", 
      "modType": "1", 
      "optionId": "1", 
      "orderDate": ""
    };
    sessionStorage.setItem("ppmCondition", JSON.stringify(this.ppmParams));
    //设置属性
    this.loadPPMConfig(this.ppmParams);

    //加载自定义js的vue页面
    this.productName(this.ppmParams);

  },
  methods: {
    //保存按钮
    async submitFun(){
       console.log("带过来的列表数据:",this.CTOInfo);
       console.log("表单数据:",this.formData);
       //获取保存参数对象
       let requestObject = this.buildObject(this.formData,this.CTOInfo,this.ppmParams,this.user);
       console.log("requestObject",requestObject);
       if(!requestObject){
         return;
       }
       //调用后台保存
       var result = await OrderService.batchEditOrderSave(requestObject);
       console.log("result",result);
       //  {"code":200,"msg":"OK","count":0,"meta":{"resultCode":"0","resultMsg":"成功"}}
       let resultCode = result.meta.resultCode;
       let resultMsg = result.meta.resultMsg;
       //返回成功提示成功，否则提示错误信息
       if(resultCode==0){
          alert("成功");
          this.$emit('close');
       }else{
         alert(resultMsg);
       }
    },
    //取消按钮
    closeFun(){
      this.$emit('close')
    },

    //为了手写校验规则能够加载自定义的vue文件js batchEditDemand10461116 page_temp_vue_mapping id:161
    async productName(params) {
      // sessionStorage.removeItem("proName");
      let result = await OrderService.getByProdId(params);
      if (result.code == 200) {
        if (result.meta && result.meta !== {}) {
          let proName = result.meta.catalogName + result.meta.tempId;
          sessionStorage.setItem("proName", proName);
        }
      }
    },

    //组装保存参数 attrArr:ppm返回加填写后的表单，selectRows:选中的销售品列表，ppmParams：请求ppm的参数，user登录人信息，
    buildObject(attrArr, selectRows, ppmParams, user)  {
        let modCount = 0;;
        let attrCount = 0;
        //页面上无字段修改不能保存
        for (let key in attrArr) {
        // attrArr.forEach((item) => {
          let item = attrArr[key];
          if (item.tableName && item.colId && item.value != '' && item.value != null) {
            if ((item.oldValue && item.oldValue != item.value) || !item.oldValue) {
              if (item.colId != '100012408') {
                modCount++;
              }
            }
          }
          if (item.colId != '100012408') {
            attrCount++;
          }
        }
        if (modCount == 0 && attrCount != 0) {
          alert("页面无修改！")
          return false;
        } else {
          //返回的请求参数
          let requestObject = {};
          requestObject.staffId = user.staffId;
          requestObject.custId = selectRows[0].custId;
          let orderItemIdArr = [];
          //拼装 this.orderItemIds
          for (let i in selectRows) {
            orderItemIdArr.push(selectRows[i].orderItemId);
          }
          this.orderItemIds =  orderItemIdArr.toString();;
          requestObject.orderItemIds = this.orderItemIds;
          console.log("this.orderItemIds",this.orderItemIds)
          //获取orderItemModifys
          let orderItemModifys = this.getOrderItemModifys(attrArr, selectRows, ppmParams, user);
          if(orderItemModifys && orderItemModifys.length>0){
              requestObject.orderItemModifys = orderItemModifys;
          }
          //获取orderItemModifyArrs
          let orderItemAttrModifys = this.getOrderItemAttrModifys(attrArr, selectRows, ppmParams, user);
          console.log('orderItemAttrModifys',orderItemAttrModifys)
          if(orderItemAttrModifys && orderItemAttrModifys.length>0){
              requestObject.orderItemAttrModifys = orderItemAttrModifys;
          }
          return requestObject;
        }
      },

      //获取订单项修改记录列表【每次提交只插入一条记录】
      getOrderItemModifys(attrArr, selectRows, ppmParams, user) {
        let orderItemModifyArr = [];
        let orderItemModify = {};
        // orderItemModify.serviceOfferId = ppmParams.serviceOfferId;
        orderItemModify.orderItemId = this.orderItemIds;
        orderItemModify.modReson = "批量修改需求单信息";
				orderItemModify.modComment = "批量修改需求单信息";//变更原因
        orderItemModify.modOldOrderNbr = selectRows[0].custSoNumber;
        orderItemModify.modTypeFlag = "3";
        orderItemModifyArr.push(orderItemModify)
        return orderItemModifyArr;
      },

      //获取订单项属性修改记录列表【所有修改的（非空的表单值）属性都放在这个里面提交到后台，所以这个有多条记录】
      getOrderItemAttrModifys(attrArr) {
        let orderItemAttrModifyArr = [];

        for (let key in attrArr) {
          let item = attrArr[key];
          let obj = {};
          if (item.tableName && item.colId && item.value != '' && item.value != null) {
            if ((item.oldValue && item.oldValue != item.value) || !item.oldValue) {
              let attrid = '';
              if (item.id.split('-').length > 1) {
                attrid = item.id.split('-')[1];
              } else {
                attrid = item.id;
              }
              obj.attrId = attrid;
              obj.attrValue = item.value;
              obj.attrCd = item.fieldId;
              if (item.attrRoleCd) {
                obj.roleCd = item.attrRoleCd;
              } else {
                obj.roleCd = '0';
              }
              orderItemAttrModifyArr.push(obj)
            }
          }
        }

        return orderItemAttrModifyArr;
      },

  },
}
</script>